/*
 * ThreadLocalInterceptor.java
 * Copyright 2021 Qunhe Tech, all rights reserved.
 * Qunhe PROPRIETARY/CONFIDENTIAL, any form of usage is subject to approval.
 */

package cn.org.itool.web.interceptor;

import cn.org.itool.web.constent.DistCommonConstant;
import cn.org.itool.web.context.RequestContext;
import cn.org.itool.web.context.ZeusRequest;
import cn.org.itool.web.util.RequestAttrUtil;
import cn.org.itool.web.util.RequestUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


public class ThreadLocalInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        DistCommonConstant.requestTL.set(request);
        DistCommonConstant.responseTL.set(response);
        // 将公共参数封装成ZeusRequest
        ZeusRequest zeusRequest = getZeusRequest(request);
        RequestContext.bindRequest(zeusRequest);
        return true;
    }

    /**
     * 将公共参数封装成ZeusRequest
     */
    private ZeusRequest getZeusRequest(HttpServletRequest request) {

        ZeusRequest zeusRequest = new ZeusRequest();

        zeusRequest.setToken(RequestAttrUtil.getTokenFromRequest());
        zeusRequest.setUserId(RequestAttrUtil.getUserIdFromRequest());
        zeusRequest.setIp(RequestUtil.getLastIp(request));
        zeusRequest.setCurrentUrl(request.getRequestURI());
        zeusRequest.setUserAgent(request.getHeader("User-Agent"));
        zeusRequest.setReferUrl(request.getHeader("Referer"));
        return zeusRequest;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView){
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        RequestContext.unbindRequest();
    }

}
